# LuckPay Web Manage System
#
# Copyright (c) 2016 Lucky Byte, Inc.
#
express = require 'express'
pgsql   = require 'pg'
moment  = require 'moment'
fs      = require 'fs'
mkdirp  = require 'mkdirp'
path    = require 'path'
router = express.Router()
module.exports = router


query = (req, res, next) ->
    where_clause = "(
        o.uuid like $1 or o.notes like $1 or
        case
            when t.chnl in (1,4) then
                json_extract_path_text(t.i_pkt, '42') like $1 or
                json_extract_path_text(t.i_pkt, '41') like $1
        end or
        case
            when t2.chnl = 3 then
                json_extract_path_text(t2.i_pkt, 'merId') like $1 or
                json_extract_path_text(t2.i_pkt, 'orderId') like $1
        end
    )"
    today = moment().format('YYYY-MM-DD')
    # 如果没有提供日期，则仅查询当日
    res.locals.start_date = req.body.start_date or \
        req.query.start_date or moment().format('YYYY-MM-DD')
    res.locals.end_date = req.body.end_date or \
        req.query.end_date or moment().format('YYYY-MM-DD')

    where_clause += " and o.sys_time::date >= '#{res.locals.start_date}'"
    where_clause += " and o.sys_time::date <= '#{res.locals.end_date}'"

    table_name = 'pay_p1_order'
    trlist_table = 'pay_trlist_hist'
    if res.locals.start_date is today and res.locals.end_date is today
        table_name = 'pay_p1_order'
        trlist_table = 'pay_trlist'

    # 通过状态过滤
    res.locals.status = req.body.status or req.query.status or ''
    if res.locals.status.length > 0
        where_clause += " and o.status = #{res.locals.status}"

    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)

    # 导出时不用计算总数
    if not req._export
        await client.query \
            "select count(o.*)::int as count
                from #{table_name} as o
                left join #{trlist_table} as t on
                    t.uuid = o.t20_uuid and t.incoming = true
                left join #{trlist_table} as t2 on
                    t2.uuid = o.t40_uuid and t2.incoming = false
            where #{where_clause}", [
                "%#{res.locals.keyword}%"
            ], defer err, result
        if err then done(client); return next(err)
        res.locals.total = result.rows[0].count

    # 如果是导出，则查询所有记录
    offset = if req._export then 0 else res.locals.offset
    limits = if req._export then 100000000 else res.locals.page_rows

    await client.query \
        "select o.*,
            case
                when t.chnl in (1,4) then
                array[
                    json_extract_path_text(t.i_pkt, '42'),
                    json_extract_path_text(t.i_pkt, '41'),
                    json_extract_path_text(t.i_pkt, '11'),
                    json_extract_path_text(t.i_pkt, '4'),
                    json_extract_path_text(t.o_pkt, '2'),
                    json_extract_path_text(t.o_pkt, '13'),
                    json_extract_path_text(t.o_pkt, '12'),
                    json_extract_path_text(t.o_pkt, '37'),
                    json_extract_path_text(t.o_pkt, '39'),
                    t.dcflag::text
                ]
            end as t20_info, t.notes as t20_notes,
            case
                when t2.chnl = 3 then
                array[
                    json_extract_path_text(t2.i_pkt, 'merId'),
                    json_extract_path_text(t2.i_pkt, 'termId'),
                    json_extract_path_text(t2.i_pkt, 'orderId'),
                    json_extract_path_text(t2.i_pkt, 'txnAmt'),
                    json_extract_path_text(t2.n_pkt, 'respCode'),
                    json_extract_path_text(t2.o_pkt, 'queryId'),
                    json_extract_path_text(t2.n_pkt, 'traceNo'),
                    json_extract_path_text(t2.i_pkt, 'accNo')
                ]
            end as t40_info, t2.notes as t40_notes,
            t2.n_pkt is not null as t40_confirm
        from #{table_name} as o
        left join #{trlist_table} as t on
            t.uuid = o.t20_uuid and t.uuid_no = 1
        left join #{trlist_table} as t2 on
            t2.uuid = o.t40_uuid and t2.incoming = false and
            json_extract_path_text(t2.trinfo, 'code')::text = 't40'
        where #{where_clause}
        order by o.serial desc offset $2 limit $3", [
            "%#{res.locals.keyword}%", offset, limits
        ], defer err, result
    if err then done(client); return next(err)
    done()

    res.locals.records = result.rows
    next()


router.all '/', query, (req, res, next) ->
    res.locals.stat_title = '消费代付明细'
    res.render 'trstat/p1_order'


# 设置导出标志，导出时不用分页查询
router.all '/export', (req, res, next) ->
    req._export = true
    next()


router.all '/export', query, (req, res, next) ->
    # 下载文件保存路径和文件名
    dirname = settings.dnload_path + "/trstat"
    mkdirp.sync(dirname)
    today = moment().format('YYYY-MM-DD')
    dnfile = "#{dirname}/p1_order-#{today}.txt"

    lines = []
    for record in res.locals.records
        line = "#{record.sys_time.format('YYYYMMDDHHmmss')},"
        line += "#{record.t20_info[0] || ''},"
        line += "#{record.t20_info[1] || ''},"
        line += "#{record.t20_info[2] || ''},"
        line += "#{parseInt(record.t20_info[3] || '0') / 100},"
        line += "#{record.t20_info[4] || ''},"
        line += "#{record.t20_info[5] || ''},"
        line += "#{record.t20_info[6] || ''},"
        line += "#{record.t20_info[7] || ''},"
        line += "#{record.t20_info[8] || ''},"
        line += "#{record.t20_info[9] || ''},"
        if record.t40_info
            line += "#{record.t40_info[0] || ''},"
            line += "#{record.t40_info[1] || ''},"
            line += "#{record.t40_info[2] || ''},"
            line += "#{parseInt(record.t40_info[3] || '0') / 100},"
            line += "#{record.t40_info[4] || ''},"
            line += "#{record.t40_info[5] || ''},"
            line += "#{record.t40_info[6] || ''},"
            line += "#{record.t40_info[7] || ''}"
        else
            line += ",,,,,,,"
        lines.push line

    fs.writeFileSync dnfile, lines.join "\n"
    await res.download dnfile, path.basename(dnfile), defer err
    fs.unlink dnfile
    res.end()
